package com.geek.novel.activity.base

import android.os.Bundle
import android.os.Message
import android.view.View
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.app.SkinAppCompatDelegateImpl
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.geek.novel.fragment.BaseFragment
import com.geek.novel.utils.StatusBarUtil
import com.geek.novel.view.loading.LoadingDialogUtil


open class BaseActivity: EventActivity(), View.OnClickListener {

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)

		//初始化loading弹框的对象
		LoadingDialogUtil.getInstance().init(this)

		//禁止横屏
//		requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
		this.onCreateActivity()
		//初始化参数
		this.initData(savedInstanceState)

		//发起请求
		this.firstRequest(savedInstanceState)

	}

	override fun setContentView(layoutResID: Int) {
		super.setContentView(layoutResID)
		
		//附加控件
		this.attachView()
		//绑定事件
		this.bindEvent()
		
	}


	override fun onResume() {
		super.onResume()
		//重新初始化loading弹框的对象,这里是因为每次进入其他页码的话，activity会隐藏在背面，导致弹框弹不出来，所以每次都刷新一次
		LoadingDialogUtil.getInstance().init(this)
	}

	/**初始化Activity的回调事件*/
	protected open fun onCreateActivity(){
		//沉浸式菜单栏
		StatusBarUtil.setTransparent(this)
	}
	/**附加控件*/
	protected open fun attachView(){}
	/**初始化数据*/
	protected open fun initData(params: Bundle?){}
	/**绑定事件*/
	protected open fun bindEvent(){}
	/**发起请求*/
	protected open fun firstRequest(params: Bundle?){}

	/**
	 * 点击事件
	 */
	override fun onClick(v: View) {
		clickEvent(v.id, v)
	}

	/**绑定点击事件的回调*/
	protected open fun clickEvent(id: Int, v: View){
	}
	
	fun replaceFrag(resId: Int, fragment: BaseFragment){
		supportFragmentManager.inTransaction {
			//获取所有fragment列表
			val list: List<Fragment> = supportFragmentManager.fragments
			//遍历是否匹配入参，并把所有都hide掉
			var isMatched = false
			for (item in list){
				if(item == fragment){
					isMatched = true
				}else{//不匹配的隐藏掉
					this.hide(item)
					fragment.onHide()
				}
			}
			//不匹配则新增数据
			if(!isMatched){
				//add会出发生命周期
				this.add(resId, fragment)
			}else{//不是add的话，直接show
				this.show(fragment)
				fragment.onShow()
			}
		}
	}
	protected fun popFrag(){
		if(supportFragmentManager.fragments.size > 1){
			supportFragmentManager.popBackStack()
		}
	}
	
	private inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> Unit) {
		val fragmentTransaction = beginTransaction()
		fragmentTransaction.func()
		fragmentTransaction.commit()
	}
	
	/**换肤支持*/
	override fun getDelegate(): AppCompatDelegate {
		return SkinAppCompatDelegateImpl.get(this, this)
	}

}